package com.ruoyi.system.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Redis分布式锁工具类
 * 
 * @author ruoyi
 * @date 2025-01-13
 */
@Component
public class RedisLockUtil
{
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    private static final String LOCK_PREFIX = "lock:";
    
    /**
     * 获取锁
     * 
     * @param key 锁的key
     * @param value 锁的value（用于验证是否是同一个持有者）
     * @param expireTime 锁过期时间（秒）
     * @return 是否获取成功
     */
    public boolean lock(String key, String value, long expireTime)
    {
        String lockKey = LOCK_PREFIX + key;
        Boolean result = redisTemplate.opsForValue()
            .setIfAbsent(lockKey, value, expireTime, TimeUnit.SECONDS);
        return result != null && result;
    }
    
    /**
     * 获取锁（自动生成value）
     */
    public String tryLock(String key, long expireTime)
    {
        String value = UUID.randomUUID().toString();
        boolean success = lock(key, value, expireTime);
        return success ? value : null;
    }
    
    /**
     * 释放锁
     * 
     * @param key 锁的key
     * @param value 锁的value（必须与获取时的value一致）
     * @return 是否释放成功
     */
    public boolean unlock(String key, String value)
    {
        String lockKey = LOCK_PREFIX + key;
        
        // 使用Lua脚本保证原子性
        String luaScript = 
            "if redis.call('get', KEYS[1]) == ARGV[1] then " +
            "    return redis.call('del', KEYS[1]) " +
            "else " +
            "    return 0 " +
            "end";
        
        DefaultRedisScript<Long> script = new DefaultRedisScript<>();
        script.setScriptText(luaScript);
        script.setResultType(Long.class);
        
        Long result = redisTemplate.execute(script, 
            Collections.singletonList(lockKey), 
            value);
        
        return result != null && result == 1;
    }
    
    /**
     * 尝试获取锁并执行任务
     * 
     * @param key 锁的key
     * @param expireTime 锁过期时间（秒）
     * @param task 要执行的任务
     * @return 执行结果
     */
    public <T> T executeWithLock(String key, long expireTime, LockTask<T> task) throws Exception
    {
        String value = tryLock(key, expireTime);
        
        if (value == null) {
            throw new RuntimeException("获取锁失败，操作太频繁，请稍后再试");
        }
        
        try {
            return task.execute();
        } finally {
            unlock(key, value);
        }
    }
    
    /**
     * 锁任务接口
     */
    @FunctionalInterface
    public interface LockTask<T>
    {
        T execute() throws Exception;
    }
}

